go to previous page   go to home page   go to next page

Answer:

JLabel fatLabel    with    JTextField inFat

JLabel calLabel    with    JTextField inCal

JLabel perLabel    with    JTextField outPer

Adding Components to JPanels

GUI with panels

The idea is to have five panels, one for each pair of label and text field, and a panel each for the heading and the do it button. The picture shows this grouping. (The lines around the panels do not appear in the actual GUI.)

Use add() to place components in a panel. FlowLayout is the default layout manager for JPanel. Use setLayout() only if you want a different layout manager.

public class PercentFatPan extends JFrame implements ActionListener
{
  JLabel heading  = new JLabel("Percent of Calories from Fat");
  JLabel fatLabel = new JLabel("Enter grams of fat:   ");
  JLabel calLabel = new JLabel("Enter total calories: ");
  JLabel perLabel = new JLabel("Percent calories from fat: ");

  JTextField inFat  = new JTextField( 7 );
  JTextField inCal  = new JTextField( 7 );
  JTextField outPer = new JTextField( 7 );

  JButton doit = new JButton("Do It!");
  
  // New: the five panels
  
  JPanel hedPanel = new JPanel();
  JPanel fatPanel = new JPanel();
  JPanel calPanel = new JPanel();
  JPanel perPanel = new JPanel();   
  JPanel butPanel = new JPanel();   
 
  public PercentFatPanel()   
  {  
    setTitle( "Calories from Fat" );
    outPer.setEditable( false );   
    setLayout( new FlowLayout() );   // set layout manager for the JFrame

    // New: Add components to each panel

    hedPanel.add( heading );
    
    fatPanel.add(  );
    fatPanel.add(  );

    calPanel.add(  );
    calPanel.add(  );

    perPanel.add(  );
    perPanel.add(  );

    butPanel.add( doit );
  
   . . . . .
   
 }

QUESTION 5:

Decide which components should be added to each panel, then click the button to see if you are correct.

At this point, the label and button components have been added to the five panels, but the panels have not yet been added to the frame.